/**
 * 商品管理-商品查询
 */
var queryGoodsSearch = function() {
	var queryGoodsFieldSet = new Ext.form.FieldSet({
				id : 'queryGoodsFieldSet',
				title : '查询条件',
				collapsible : true,// 可折叠
				buttonAlign : 'center',
				keys : [{
							key : 13, // 13代表回车
							fn : queryGoods,
							scope : this
						}],
				items : [{
					layout : 'column',
					border : false,
					items : [{
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											id : "goodsManager_goodsName",
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '商品名称',
											name : "goodsName"
										}, {
											id : 'goodsCategory_goodsCategoryId',
											xtype : 'goodsCategoryCmb',
											fieldLabel : "分类名称",
											allowBlank : true,
											hiddenName : 'goodsCategoryId',
											showValue : true,
											existall : true,
											defaultFirstRow : 1,
											statusArr : [0, 1]
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											id : "goodsManager_goodsCode",
											anchor : '100%',
											fieldLabel : '商品编码',
											name : "goodsCode"
										}, {
											xtype : 'dataDictionaryCmb',
											anchor : '100%',
											fieldLabel : "商品特性",
											editable : false,
											autoLoad : false,
											existall : true,
											defaultFirstRow : 1,
											hiddenName : 'goodsLable',
											dictionaryType : PmsUtil.goods_lable
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
									xtype : 'localcommonbox',
									anchor : '100%',
									fieldLabel : '商品状态',
									hiddenName : 'goodsStatus',
									loaclarr : [['0', '未上架'], ['1', '已上架'],
											['2', '已下架'], ['', '全部']]
								}, {
									columnWidth : .25,
									layout : 'form',
									border : false,
									items : [{
										layout : 'column',
										border : false,
										items : [{
													text : '查询',
													xtype : 'button',
													width : 80,
													handler : function() {
														queryGoods();
													},
													style : {
														marginLeft : "50px",
														marginRight : "10px"
													}
												}, {
													text : '重置',
													xtype : 'button',
													width : 80,
													handler : function() {
														Ext
																.getCmp('queryGoodsForm')
																.getForm()
																.reset();
													}
												}]
									}]
								}]
							}]
				}]
			});
	fieldSetListeners(['queryGoodsFieldSet', 'queryGoodsForm',
					'goodsManagerGrid'], [0.16, 0.84]);

	var queryGoodsForm = new Ext.form.FormPanel({
				id : 'queryGoodsForm',
				anchor : '100% 16%',
				frame : true,
				labelAlign : 'right',
				bodyBorder : false,
				items : [queryGoodsFieldSet]
			});
	return queryGoodsForm;
};

/**
 * grids
 */
var goodsManagerGrid = function() {
	var goodsManagerSm = new Ext.grid.CheckboxSelectionModel();// 创建选择模式对象
	// 定义表的每列（对应表头信息）
	var goodsManagerCm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
			{
				dataIndex : "id",
				header : "商品编号",
				sortable : true,
				width : 60
			}, {
				dataIndex : "goodsName",
				header : "商品名称",
				sortable : true,
				width : 120,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="商品名称:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "goodsSubName",
				header : "商品副标题",
				sortable : true,
				width : 180,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="商品副标题:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "goodsCode",
				header : "商品编码",
				sortable : true,
				width : 70
			}, {
				dataIndex : "goodsPic",
				header : "商品图片",
				sortable : true,
				width : 100,
				renderer : function(value) {
					return PmsUtil.ShowPicture(value);
				}
			}, {
				dataIndex : "goodsBasePic",
				header : "商品白底图",
				sortable : true,
				width : 100,
				renderer : function(value) {
					return PmsUtil.ShowPicture(value);
				}
			}, {
				dataIndex : "goodsDefalutPrice",
				header : "商品默认价格",
				sortable : true,
				width : 90,
				renderer : function(value) {
					return PmsUtil.Price(value);
				}
			}, {
				dataIndex : "goodsStatus",
				header : "商品状态",
				sortable : true,
				width : 60,
				renderer : function(value) {
					if (value == 1) {
						return '<div style="color:red;">'
								+ PmsUtil.GoodsStatus(value) + '</div>';
					}
					return PmsUtil.GoodsStatus(value);
				}
			}, {
				dataIndex : "goodsType",
				header : "商品类型",
				sortable : true,
				width : 60,
				renderer : function(value) {
					return PmsUtil.GoodsType(value);
				}
			}, {
				dataIndex : "goodsDescUrl",
				header : "商品详情地址",
				sortable : true,
				width : 110,
				renderer : function(value, meta, record) {
					if (value) {
						var p = '<a href="#"  onClick="javascript:window.open(\''
								+ value + '\')" >' + value + '</a>';
						return p;
					}
				}
			}, {
				dataIndex : "goodsOrder",
				header : "商品排序",
				sortable : true,
				width : 50,
				editor : {
					xtype : 'numberfield'
				}
			}, {
				dataIndex : "goodsEnName",
				header : "商品英文名称",
				sortable : true,
				width : 80
			}, {
				dataIndex : "goodsLable",
				header : "商品特性",
				sortable : true,
				width : 70,
				renderer : function(value) {
					return PmsUtil.GoodsLable(value);
				}
			}, {
				dataIndex : "categoryName",
				header : "分类名称",
				sortable : true,
				width : 80
			}, {
				dataIndex : "goodsDefalutSweet",
				header : "商品甜度",
				sortable : true,
				width : 70
			}, {
				dataIndex : "goodsDefalutWeight",
				header : "商品默认显示规格",
				sortable : true,
				width : 110
			}, {
				dataIndex : "createdDate",
				header : "创建时间",
				sortable : true,
				width : 110
			}, {
				dataIndex : "createdName",
				header : "创建人",
				sortable : true,
				width : 70
			}, {
				dataIndex : "updatedDate",
				header : "修改时间",
				sortable : true,
				width : 110
			}, {
				dataIndex : "updatedName",
				header : "修改人",
				sortable : true,
				width : 70
			}, {
				header : "管理",
				width : 400,
				dataIndex : "id",
				sortable : false,
				renderer : function(j, i, g, m, h) {
					var l = g.data.id;
					var goodsName = g.data.goodsName;
					var goodsCode = g.data.goodsCode;
					var goodsStatus = g.data.goodsStatus;
					var k = "";
					if (l != 0) {
						if (isGranted("goodsManager_修改商品")) {
							k += '&nbsp;&nbsp;<a href="#" onclick="updateGoods('
									+ l + ');" >修改</a>';
						}

						if (isGranted("goodsManager_删除商品")) {
							if (goodsStatus == "1") {
								k += '&nbsp;&nbsp;<a href="#" onclick="updGoodsToDownById('
										+ l
										+ ','
										+ "2"
										+ ','
										+ "'下架'"
										+ ')\" >下架</a>';
							}

						}

						if (isGranted("goodsManager_尺寸管理")) {
							k += '&nbsp;&nbsp;<a href="#" onclick="priceSizeManager('
									+ l
									+ ",'"
									+ goodsName
									+ "','"
									+ goodsCode
									+ "')\" >尺寸管理</a>";
						}

						if (isGranted("goodsManager_图片展示")) {
							k += '&nbsp;&nbsp;<a href="#" onclick="showPicture('
									+ l + ",'" + goodsName + "')\" >商品图片</a>";
						}
						if (isGranted("goodsLableManager_商品标签管理")) {
							k += '&nbsp;&nbsp;<a href="#" onclick="selectGoodsLableManager('
									+ l + ",'" + goodsName + "')\" >商品标签管理</a>";
						}
					}
					return k;
				}
			}]);

	// 定义分析器
	var goodsManagerReader = new Ext.data.JsonReader({
				totalProperty : "totalCount",
				root : "list",
				fields : [{
							name : "id"
						}, {
							name : "goodsName"
						}, {
							name : "goodsSubName"
						}, {
							name : "goodsCode"
						}, {
							name : 'goodsDescUrl'
						}, {
							name : "goodsPic"
						}, {
							name : "goodsBasePic"
						}, {
							name : "goodsCategoryId"
						}, {
							name : "goodsDefalutPrice"
						}, {
							name : "goodsType"
						}, {
							name : "goodsStatus"
						}, {
							name : "goodsOrder"
						}, {
							name : "goodsEnName"
						}, {
							name : "goodsLable"
						}, {
							name : "categoryName"
						}, {
							name : "createdDate"
						}, {
							name : "createdName"
						}, {
							name : "updatedDate"
						}, {
							name : "updatedName"
						}, {
							name : "goodsDefalutSweet"
						}, {
							name : "goodsDefalutWeight"
						}]
			});

	// 取数据store
	var goodsViewStore = new Ext.data.Store({
				autoLoad : true,// 要加载数据必须设置为true
				proxy : new Ext.data.HttpProxy({
							url : __ctxPath + "/goodsManager/selectAllGoods"
						}),
				remoteSort : false,
				baseParams : {
					start : 0,
					limit : 25
				},
				listeners : {
					beforeload : {
						fn : function(thiz, options) {
							Ext.apply(thiz.baseParams, Ext
											.getCmp('queryGoodsForm').getForm()
											.getValues());
						}
					}
				},
				reader : goodsManagerReader
			});

	// 定义grid的toolbar
	var goodsTb = new Ext.Toolbar({
				height : 25,
				items : []
			});
	goodsTb.add(new Ext.scm.Button({
				text : "商品添加",
				width : 80,
				pressed : true,
				hsValue : 'goodsManager_新建商品',
				iconCls : "btn-add",
				listeners : {
					"click" : function() {
						addGoods();
					}
				}
			}));
	goodsTb.add(new Ext.Toolbar.Spacer());
	goodsTb.add(new Ext.scm.Button({
				text : "排序批量修改",
				iconCls : "btn-edit",
				width : 80,
				pressed : true,
				hsValue : "goodsManager_排序批量修改",
				listeners : {
					"click" : function() {
						updateGoodsOrder();
					}
				}
			}));
	goodsTb.add(new Ext.Toolbar.Spacer());
	goodsTb.add(new Ext.scm.Button({
				text : "刷 新",
				iconCls : "btn-refresh",
				width : 80,
				hsValue : 'goodsManager_刷新',
				pressed : true,
				handler : function() {
					queryGoods();
				}
			}));

	var goodsManagerGrid = new Ext.grid.EditorGridPanel({
				id : 'goodsManagerGrid',
				store : goodsViewStore,
				cm : goodsManagerCm,
				sm : goodsManagerSm,
				autoScroll : true,
				loadMask : true,
				stripeRows : true,
				columnLines : true,
				clicksToEdit : 1,
				loadMask : {
					msg : "正在加载数据，请稍侯……"
				},
				viewConfig : {
					emptyText : '没有您想要的数据!'
				},
				anchor : '100% 86%',
				frame : true,
				tbar : goodsTb,
				bbar : new PG.PagingBar({
							id : 'goodsManagerGridPage',
							store : goodsViewStore
						})
			});
	var smodel = goodsManagerGrid.getSelectionModel();
	smodel.onEditorKey = function(field, e) {
		var k = e.getKey(), newCell, g = smodel.grid, ed = g.activeEditor;
		if (k == e.TAB) {
			e.stopEvent();
			ed.completeEdit();
			if (e.shiftKey) {
				newCell = g.walkCells(ed.row, ed.col - 1, -1,
						smodel.acceptsNav, smodel);
			} else {
				newCell = g.walkCells(ed.row, ed.col + 1, 1, smodel.acceptsNav,
						smodel);
			}
			if (ed.col == 1) {
				if (e.shiftKey) {
					newCell = g.walkCells(ed.row, ed.col + 1, -1,
							smodel.acceptsNav, smodel);
				} else {
					newCell = g.walkCells(ed.row, ed.col + 1, 1,
							smodel.acceptsNav, smodel);
				}
			}
		} else if (k == e.UP) {
			e.stopEvent();
			ed.completeEdit();
			newCell = g.walkCells(ed.row - 1, ed.col, -1, smodel.acceptsNav,
					smodel);
			if (ed.col == 1) {
				newCell = g.walkCells(ed.row, ed.col + 1, -1,
						smodel.acceptsNav, smodel);
			}
		} else if (k == e.DOWN) {
			e.stopEvent();
			ed.completeEdit();
			newCell = g.walkCells(ed.row + 1, ed.col, 1, smodel.acceptsNav,
					smodel);
			if (ed.col == 1) {
				newCell = g.walkCells(ed.row, ed.col + 1, 1, smodel.acceptsNav,
						smodel);
			}
		}

		if (newCell) {
			g.startEditing(newCell[0], newCell[1]);
		}
	};
	return goodsManagerGrid;
};

// 添加
function addGoods() {
	try {
		addOrUpdGoods(null, "新增商品").show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/goods/goodsForm.js'], function() {
					addOrUpdGoods(null, "新增商品").show();
				});
	}
}

/**
 * 修改商品
 */
function updateGoods(goodsId) {
	try {
		addOrUpdGoods(goodsId, "编辑商品").show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/goods/goodsForm.js'], function() {
					addOrUpdGoods(goodsId, "编辑商品").show();
				});
	}
}

// 下架商品
function updGoodsToDownById(goodsId, goodsStatus, message) {
	Ext.Msg.confirm("信息确认", "是否" + message + "该商品?", function(btn) {
				if (btn == "yes") {
					var optionMask = new Ext.LoadMask(Ext.getBody(), {
								msg : "正在处理,请稍后..."
							});
					optionMask.show();
					Ext.Ajax.request({
								url : __ctxPath
										+ "/goodsManager/updGoodsStatusById",
								params : {
									goodsId : goodsId,
									goodsStatus : goodsStatus
								},
								method : "post",
								success : function(response) {
									optionMask.hide();
									var jsonData = Ext.util.JSON
											.decode(response.responseText);
									if (jsonData.success) {
										Ext.MessageBox.show({
													title : "信息提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.INFO
												});
										queryGoods();
									} else {
										Ext.MessageBox.show({
													title : "错误提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.ERROR
												});
									}
								},
								failure : function(response) {
									optionMask.hide();
									Ext.MessageBox.show({
												title : "操作信息",
												msg : "服务器请求异常,请稍后再试!",
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.ERROR
											});
								}
							});
				}
			});

}

// 查询
function queryGoods() {
	var form = Ext.getCmp("queryGoodsForm");
	if (form.getForm().isValid()) {
		var grid = Ext.getCmp("goodsManagerGrid");
		var store = grid.store;
		var pagesize = Ext.getCmp('goodsManagerGridPage').pageSize;
		store.load({
					params : {
						start : 0,
						limit : pagesize
					}
				});
	}
}

/**
 * 尺寸管理
 * 
 * @param {}
 *            id
 * @param {}
 *            goodsName
 * @param {}
 *            goodsCode
 */
function priceSizeManager(id, goodsName, goodsCode) {
	var centerPanel = App.getContentPanel();
	var tab = centerPanel.getItem(PmsUtil.GOODS_PRICE_SIZE);
	var createNewTab = new CreatNewTab(PmsUtil.GOODS_PRICE_SIZE, '尺寸管理');
	if (tab == null) {
		createNewTab.createNew(tab);
	} else {
		createNewTab.createOld(tab,
				['goodsPriceSizeForm', 'goodsPriceSizeGrid']);
	}
	Ext.Loader.load([__ctxPath + '/js/goods/goodsSize.js'], function() {
				Ext.getCmp("centerTabPanel").getActiveTab().add(
						goodsPriceSizeForm(id, goodsName, goodsCode),
						goodsPriceSizeGrid(id, goodsCode));
				Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
			});
}

/**
 * 图片展示
 * 
 * @param {}
 *            id
 */
function showPicture(id, goodsName) {
	var centerPanel = App.getContentPanel();
	var tab = centerPanel.getItem(PmsUtil.SHOW_GOODS_PICTURE);
	var createNewTab = new CreatNewTab(PmsUtil.SHOW_GOODS_PICTURE, '商品图片查询');
	if (tab == null) {
		createNewTab.createNew(tab);
	} else {
		createNewTab.createOld(tab, ['showGoodsPictureForm',
						'showGoodsPictureGrid']);
	}
	Ext.Loader.load([__ctxPath + '/js/goods/showGoodsPicture.js'], function() {
				Ext.getCmp('goodsPic_goodsId').setValue(id);
				Ext.getCmp('goodsPic_goodsId').setRawValue(goodsName);
			});
};
/**
 * 排序批量修改
 */
function updateGoodsOrder() {
	var modiRecords = Ext.getCmp("goodsManagerGrid").getStore()
			.getModifiedRecords();
	if (modiRecords.length == 0) {
		saveMask.hide();
		Ext.MessageBox.show({
					title : '提示',
					msg : '当前没有数据修改',
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	};

	var goodsOrderUpdateArr = new Array();
	for (var i = 0; i < modiRecords.length; i++) {
		var temrecord = new Ext.data.Record();
		temrecord.set("id", modiRecords[i].data.id);
		temrecord.set("goodsOrder", modiRecords[i].data.goodsOrder);
		goodsOrderUpdateArr.push(temrecord.data);
	}
	var jsonList = Ext.encode(goodsOrderUpdateArr);

	Ext.Msg.confirm("信息确认", "是否批量修改商品排序？", function(btn) {
				if (btn == 'yes') {
					var optionMask = new Ext.LoadMask(Ext.getBody(), {
								msg : "正在处理,请稍后..."
							});
					optionMask.show();
					Ext.Ajax.request({
								url : __ctxPath
										+ "/goodsManager/updateGoodsOrder",
								params : {
									jsonList : Ext.util.Format
											.htmlDecode(jsonList).trim()
								},
								method : "post",
								success : function(response) {
									optionMask.hide();
									var jsonData = Ext.util.JSON
											.decode(response.responseText);
									if (jsonData.success) {
										Ext.MessageBox.show({
													title : "信息提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.INFO
												});
										queryGoods()
									} else {
										Ext.MessageBox.show({
													title : "错误提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.ERROR
												});
									}
								},
								failure : function(response) {
									optionMask.hide();
									Ext.MessageBox.show({
												title : "操作信息",
												msg : "服务器请求异常,请稍后再试!",
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.ERROR
											});
								}
							});
				}
			});
}

/**
 * 查询商品标签信息
 * 
 * @param {}
 *            goodsLableId
 */
function selectGoodsLableManager(id, goodsName) {
	var centerPanel = App.getContentPanel();
	var tab = centerPanel.getItem(PmsUtil.GOODS_LABLE_MANAGER_ID);
	var createNewTab = new CreatNewTab(PmsUtil.GOODS_LABLE_MANAGER_ID, '商品标签查询');
	if (tab == null) {
		createNewTab.createNew(tab);
	} else {
		createNewTab.createOld(tab, ['queryGoodsLableForm',
						'goodsLableManagerGrid']);
	}
	Ext.Loader.load([__ctxPath + '/js/goods/goodLableManager.js'], function() {
				Ext.getCmp('goodsLable_goodsId').setValue(id);
				Ext.getCmp('goodsLable_goodsId').setRawValue(goodsName);
			});
}

Ext.getCmp("centerTabPanel").getActiveTab().add(queryGoodsSearch(),
		goodsManagerGrid());
Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
